package com.huawei.esdk.oa.device.exchange;

import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.log4j.Logger;
import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.BasePropertySet;
import microsoft.exchange.webservices.data.CalendarFolder;
import microsoft.exchange.webservices.data.CalendarView;
import microsoft.exchange.webservices.data.ConflictResolutionMode;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExtendedProperty;
import microsoft.exchange.webservices.data.ExtendedPropertyDefinition;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.ItemId;
import microsoft.exchange.webservices.data.MapiPropertyType;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.ServiceResponseException;
import microsoft.exchange.webservices.data.WellKnownFolderName;
import com.huawei.esdk.oa.device.exchange.common.ExchangeServiceFactory;
import com.huawei.esdk.oa.device.exchange.convert.ExchangeConfMgrConvert;
import com.huawei.esdk.platform.common.SDKErrorCode;
import com.huawei.esdk.platform.common.SDKResult;
import com.huawei.esdk.platform.common.utils.ApplicationContextUtil;
import com.huawei.esdk.tp.common.ErrInfo;
import com.huawei.esdk.tp.device.oa.IExchangeCapability;
import com.huawei.esdk.tp.domain.model.Conference;

public class ExchangeCapability implements IExchangeCapability
{
    private ExchangeConfMgrConvert exchangeConfMgrConvert = ApplicationContextUtil.getBean("exchangeConfMgrConvert");
    
    private CalendarFolder calendarFolder;
    
    //扩展属性
    private ExtendedPropertyDefinition extendedPropertyDefinition = 
        new ExtendedPropertyDefinition(UUID.fromString("6e2e659c-008d-4687-8e3e-f7ddcebd28dc"),1, 
        MapiPropertyType.String);
    
    private static final Logger LOGGER = Logger.getLogger(ExchangeCapability.class);
    
    @Override
    public SDKResult<String> scheduleExchangeConf(Conference conferenceInfo)
    {
        SDKResult<String> result = new SDKResult<String>();
        ExchangeService service = ExchangeServiceFactory.getService();
        
        try
        {
            Appointment appointment = new Appointment(service);
            
            exchangeConfMgrConvert.convertExchangeConfModal2South(conferenceInfo, appointment);
            

            //把tp会议Id,eSDK名称，本机IP并保存在exchangeConf的扩展属性里
            InetAddress addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress();

            String extendInfo = conferenceInfo.getId() + "#" + ip;
            appointment.setExtendedProperty(extendedPropertyDefinition, extendInfo);

            appointment.save();
            ItemId id = appointment.getId();
            result.setErrCode(0);
            result.setResult(id.getUniqueId());
        }
        catch (Exception e)
        {
            LOGGER.error("Exchange service error", e);
            result.setErrCode(ErrInfo.SDK_SYSTEM_ERRORCODE);
        }
        
        return result;
    }
    
    @Override
    public SDKErrorCode cancelExchangeConf(String exchangeConfId)
    {
        SDKErrorCode errorCode = new SDKErrorCode();
        ExchangeService service = ExchangeServiceFactory.getService();
        
        if (null != exchangeConfId)
        {
            try
            {
                Appointment appointment = Appointment.bind(service, new ItemId(exchangeConfId));
                appointment.cancelMeeting();
                errorCode.setErrCode(0);
            }
            catch(ServiceResponseException e)
            {
                LOGGER.error("Exchange service error", e);
                errorCode.setErrCode(0);
            }
            catch (Exception e)
            {
                LOGGER.error("Exchange service error", e);
                errorCode.setErrCode(ErrInfo.SDK_SYSTEM_ERRORCODE);
            }
            
        }
        
        return errorCode;
    }
    
    @Override
    public SDKResult<String> editExchangeConf(Conference conferenceInfo)
    {
        SDKResult<String> result = new SDKResult<String>();
        ExchangeService service = ExchangeServiceFactory.getService();
        
        try
        {
            Appointment appointment = Appointment.bind(service, new ItemId(conferenceInfo.getId()));
            
            exchangeConfMgrConvert.convertExchangeConfModal2South(conferenceInfo, appointment);
            
            appointment.update(ConflictResolutionMode.AutoResolve);
            ItemId id = appointment.getId();
            result.setErrCode(0);
            result.setResult(id.getUniqueId());
        }
        catch(ServiceResponseException e)
        {
            LOGGER.error("Exchange service error", e);
            result.setErrCode(0);
        }
        catch (Exception e)
        {
            LOGGER.error("Exchange service error", e);
            result.setErrCode(ErrInfo.SDK_SYSTEM_ERRORCODE);
        }
        
        return result;
    }
    
    @Override
    public SDKResult<Map<String, Conference>> findExchangeConf(Date beginDate, Date endDate, boolean isCreatedByMe)
    {
        SDKResult<Map<String, Conference>> response = new SDKResult<Map<String, Conference>>();
        Map<String, Conference> result = new HashMap<String, Conference>();
        ExchangeService service = ExchangeServiceFactory.getService();
        
        try
        {
            if (null == calendarFolder)
            {
                calendarFolder = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
            }
            FindItemsResults<Appointment> findResults = calendarFolder.findAppointments(new CalendarView(beginDate, endDate));
            
            InetAddress addr = InetAddress.getLocalHost();
            String myIp = addr.getHostAddress();
            String esdkFlag = myIp;
            
            for (Appointment appt : findResults.getItems())
            {

                appt.load();
                appt.load(new PropertySet(BasePropertySet.FirstClassProperties, extendedPropertyDefinition));

                if (!appt.getIsCancelled())
                {

                    String extendedTpConfId = "";
                    String extendedESDKFlag = "";
                    
                    for(ExtendedProperty proper : appt.getExtendedProperties())
                    {
                        if(extendedPropertyDefinition.getId().equals( 
                            proper.getPropertyDefinition().getId()))
                        {
                           String extendedInfo = (String)proper.getValue();
                           int index = extendedInfo.indexOf("#");
                           if(-1 == index)
                           {
                               continue;
                           }
                           
                           extendedTpConfId = extendedInfo.substring(0, index);
                           extendedESDKFlag = extendedInfo.substring(index + 1);
                        }

                        
                        if(isCreatedByMe)
                        {
                            if(esdkFlag.equals(extendedESDKFlag))
                            {
                                result.put(extendedTpConfId, 
                                    exchangeConfMgrConvert.getTpConfSouth2Modal(appt));
                            }
                        }
                        else
                        {
                            result.put(extendedTpConfId, 
                                exchangeConfMgrConvert.getTpConfSouth2Modal(appt));
                        }
                    }
                    
                }

            }
            
            response.setResult(result);
        }
        catch (Exception e)
        {
            LOGGER.error("findExchangeConf method error", e);
        }
        
        return response;
    }
}
